package com.metamech.vorpal;

import java.io.IOException;
import java.io.Writer;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import com.metamech.jabber.JabberID;
import com.metamech.jabber.Session;

import edu.mobbuzz.web.facade.AuthorizationFacade;


public class UserIndex {
	private AuthorizationFacade registrationFacade;
	
	// user (String) -> User
	Hashtable userIndex ;

	// Session -> User
	Hashtable sessionIndex = new Hashtable();
	
	public User addUser(String name, String password){
		User user = getUser(name);
		if (user == null){
			user = new User(name);
		}
		
		getUserIndex().put(name,user);
		getRegistrationFacade().registerUser(name, password);
		
		return user;
	}

	public User getUser(String name){
		return (User)getUserIndex().get(name);
	}

	public User getUser(Session session){
		return (User)sessionIndex.get(session);
	}

	public void removeUser(String name){
		getUserIndex().remove(name);
	}

	public Writer getWriter(String jabberID) throws IOException {
		return getWriter(new JabberID(jabberID));
	}

	public Writer getWriter(JabberID jabberID) throws IOException {
		return getUser(jabberID.getUser()).getWriter(jabberID.getResource());
	}

	public void removeSession(Session session){
		sessionIndex.remove(session);
		if (session.getJID() == null){
			return;
		}
		getUser(session.getJID().getUser()).removeSession(session);
	}

	public void addSession(Session session){
		User user = getUser(session.getJID().getUser());
		user.addSession(session);
		sessionIndex.put(session,user);
	}

	public Hashtable getUserIndex() {
		if(userIndex==null){
			userIndex = new Hashtable();			
			List<edu.mobbuzz.daf.bean.User> userList = getRegistrationFacade().getUserList("", "");
			for (Iterator iterator = userList.iterator(); iterator.hasNext();) {
				edu.mobbuzz.daf.bean.User _user = (edu.mobbuzz.daf.bean.User) iterator.next();
				User _o = new User(_user.getUsername());
				_o.setPassword(_user.getPassword());
				userIndex.put(_user.getUsername(), _o);
			}
		}
		return userIndex;
	}

	public void setUserIndex(Hashtable userIndex) {
		this.userIndex = userIndex;
	}

	public AuthorizationFacade getRegistrationFacade() {
		if(registrationFacade==null)
			registrationFacade = new AuthorizationFacade();
		return registrationFacade;
	}

	
	
	
}